package com.tiancheng.trade.commom.mq.rabbit.producer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

/**
 * @Author: kellen
 * @Description: 生产者
 * @Date: create in 2024/11/26 11:13
 */
@Slf4j
public class RabbitProducerManager {
    private final AmqpTemplate amqpTemplate;

    /**
     * 发送延迟消息
     *
     * @param exchange
     * @param rabbitRouting 路由
     * @param message       消息体
     * @param delay         延迟时间，单位S
     */
    public void sendMessage(String exchange, String rabbitRouting, Object message, int delay) {
        this.amqpTemplate.convertAndSend(exchange, rabbitRouting, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setDelay(delay * 1000);
                return message;
            }
        });
        log.info("向路由:{}, 发送消息成功:{}", rabbitRouting, message);
    }

    public void sendMessage(String exchange, String rabbitRouting, Object message) {
        this.amqpTemplate.convertAndSend(exchange, rabbitRouting, message);
        log.info("向路由:{}, 发送消息成功:{}", rabbitRouting, message);
    }

    public void sendMessage(String exchange, String rabbitRouting, Object message, CorrelationData correlationData) {
        this.amqpTemplate.convertAndSend(exchange, rabbitRouting, message);
        log.info("向路由:{}, 发送消息成功:{}, correlationData:{}", new Object[]{rabbitRouting, message, correlationData});
    }

    public RabbitProducerManager(final AmqpTemplate amqpTemplate) {
        this.amqpTemplate = amqpTemplate;
    }
}
